<?php
/**
 * RadioStoryModel.class.php
 * 电台故事模型
 * 
 * @author  王中艺 <wangzy_smile@qq.com>
 * @date    2017-08-18
 */

namespace Common\Model;

class RadioStoryModel extends BaseModel {

    protected $trueTableName    = 't_radio_story';
    protected $cache    = true;

    /**
     * 查询条件设置
     * @param   $condition
     * @param   $tbName
     * @return  $where
     */
    function setCondition($condition, $tbName = ''){
        $tbName     = $tbName ? $tbName.'.' : '';
        $where  = [];

        //状态查询
        if(isset($condition['status']) && is_numeric($condition['status'])){
            $where[$tbName.'status']    = $condition['status'];
        }else{
            $where[$tbName.'status']    = ['neq', -1];
        }

        return $where;
    }

    /**
     * 字段处理
     * @param   $data
     * @param   $batch
     * @return  $data
     */
    static function resolveColumn($data, $batch = false){
        $status     = [1 => '正常', -1 => '已删除', 2 => '待上线'];
        $resolveColumn   = function(&$item) use ($status){
            $item['audio']   = C('SERVER_CDN').$item['audio'];
            $item['sim_title']   = cut_str($item['title'], 10);
            $item['status_text'] = $status[$item['status']];
            $item['create_date'] = date('Y-m-d', $item['create_time']);
            if($item['online_time']){
                $format     = in_array(strtolower(MODULE_NAME), ['wechat']) ? 'Y-m-d' : 'Y-m-d H:i:s';
                $item['online_date']   = date($format, $item['online_time']);
            }
            if($item['update_time'])
                $item['update_date'] = date('Y-m-d', $item['update_time']);
        };

        if($batch){
            foreach($data as &$item){
                $resolveColumn($item);
            }
        }else{
            $resolveColumn($data);
        }

        return $data;
    }

    /**
     * 列表获取
     * @param   $condition
     * @param   $page
     * @param   &$pageHtml
     * @return  $list
     */
    function getList($condition, $page = 1, &$pageHtml = false){
        $where  = $this->setCondition($condition);
        $query  = $this->where($where)->cache($this->cache);

        if($pageHtml === true){
            $Page   = new \Think\Page((clone $query)->count(), C('PAGE_COUNT'));
            $pageHtml   = $Page->angularShow();
        }

        $list   = $query->page($page, C('PAGE_COUNT'))->order('online_time desc,id desc')->select();
        $list   = self::resolveColumn($list, true);

        return $list;
    }
}